package com.example.disk.obs;

import java.io.*;

import com.obs.services.model.*;

import com.obs.services.ObsClient;
import com.obs.services.model.fs.RenameRequest;
import com.obs.services.model.fs.RenameResult;
import org.springframework.stereotype.Service;

@Service
public class ObsImp implements OBSAgent {

    private static final String ak = "A856P9G4NZSCJDPSQPLE";
    private static final String sk = "zcFgWLubQGAZCNXwJyPwArTLcmcVLn4sjBJuSQJC";
    private static final String endPoint = "obs.cn-north-4.myhuaweicloud.com";
    private static final String bucketName = "ccceeeeee";

    public ObsClient getObsClient() {
        return new ObsClient(ak, sk, endPoint);
    }

    /*
     * @description: 创建文件夹
     * @param: username
     * @param: parentPath
     * @param: dirname
     * @return: boolean
     * @author: Xiong Mian
     * @date: 2020/7/18
     */
    @Override
    // lishuai-test /test01 test02
    public boolean makeDir(String username, String parentPath, String dirname) {
        ObsClient obsClient = getObsClient();
        if(parentPath.length()==1){
            if ((obsClient.putObject(bucketName, username + parentPath + dirname+"/", new ByteArrayInputStream(new byte[0]))) != null) {
                return true;
            } else {
                return false;
            }
        }

        if ((obsClient.putObject(bucketName, username + parentPath + "/" + dirname+"/", new ByteArrayInputStream(new byte[0]))) != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean makeRootDir(String username) {
        ObsClient obsClient = getObsClient();
        if ((obsClient.putObject(bucketName, username+"/", new ByteArrayInputStream(new byte[0]))) != null) {
            return true;
        } else {
            return false;
        }
    }

    //保存文件
    @Override
    public boolean storeFile(String username, String aimPath, FileOutputStream fos) {
        return false;
    }

    /*
     * @description: 上传文件
     * @param: username
     * @param: aimPath 全路径
     * @param: file
     * @return: boolean
     * @author: Xiong Mian
     * @date: 2020/7/18
     */
    @Override
    public boolean storeFile(String username, String aimPath, String filename, InputStream is) throws FileNotFoundException {
        System.out.println("aimPath="+aimPath+" filename="+filename);
        ObsClient obsClient = this.getObsClient();
        String objectKey="";
        //主目录下特别处理
        if(aimPath.length()==1){
            objectKey = username + aimPath+filename;
        }else{
            objectKey = username + aimPath+"/"+filename;
        }

        PutObjectResult putObject = obsClient.putObject(bucketName, objectKey, is);
        if (putObject != null) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * @description: 下载文件
     * @param: username
     * @param: path
     * @param: filename
     * @return: java.io.File
     * @author: Xiong Mian
     * @date: 2020/7/18
     */
    @Override
    public File getFile(String username, String path, String filename) throws IOException {
        ObsClient obsClient = this.getObsClient();
        String objectKey="";
        if(path.length()==1){
            objectKey = username + path+filename;
        }else{
            objectKey = username + path+"/"+filename;
        }
        System.out.println("=====================================================objectKey="+objectKey);
        // 判断对象是否存在
        //boolean flag = obsClient.doesObjectExist(bucketName, objectKey);
//        if (flag) {
        ObsObject object = obsClient.getObject(bucketName, objectKey);
        if (object != null) {
            //创建输入流（读）
            InputStream objectContent = object.getObjectContent();
            //创建一个临时文件
            File file = File.createTempFile("C:\\Users\\xx\\Desktop",".tmp");
            OutputStream fileOutputStream = new FileOutputStream(file);
            //定义缓冲区
            byte[] b = new byte[1024];
            int length = 0;
            while ((length = objectContent.read(b)) != -1) {
                //进行读写的过程
                fileOutputStream.write(b, 0, length);
            }
            fileOutputStream.close();
            objectContent.close();
            return file;
        } else {
            return null;
        }
//        } else {
//            return null;
//        }
    }

    //返回输入流
    @Override
    public InputStream getInputStream(String username, String path, String filename) {
        ObsClient obsClient = this.getObsClient();
        String objectKey="";
        if(path.length()==1){
            objectKey = username + path+filename;
        }else{
            objectKey = username + path+"/"+filename;
        }
        boolean flag = obsClient.doesObjectExist(bucketName, objectKey);
        if(flag){
            return obsClient.getObject(bucketName, objectKey).getObjectContent();
        }else{
            return null;
        }
    }

    /*
     * @description: 移动文件
     * @param: username
     * @param: sourcePath
     * @param: aimPath
     * @param: filename
     * @return: boolean
     * @author: Xiong Mian
     * @date: 2020/7/18
     */
    @Override
    public boolean moveFile(String username, String sourcePath, String aimPath, String filename) throws IOException {
        ObsClient obsClient = this.getObsClient();
        //目标文件的键值
        String aimObjectKey="";
        if(aimPath.length()==1){
            aimObjectKey = username + aimPath+filename;
        }else{
            aimObjectKey = username + aimPath+"/"+filename;
        }
        System.out.println("aimkey="+aimObjectKey+ " username="+username+" aimPath="+aimPath+ " filename="+filename);
        String oldObjectKey="";
        if(sourcePath.length()==1){
            oldObjectKey = username + sourcePath+filename;
        }else{
            oldObjectKey = username + sourcePath+"/"+filename;
        }
        //创建文件输入流
        System.out.println("oldkey="+oldObjectKey+ " username="+username+" sourcePath="+sourcePath+ " filename="+filename);
        InputStream is = obsClient.getObject(bucketName,oldObjectKey).getObjectContent();
        //在目标位置创建与原文件相同的文件
        obsClient.putObject(bucketName, aimObjectKey, is);

        deleteFile(username,sourcePath,filename);

        return true;
    }

    @Override
    public boolean moveDir(String username, String sourcePath, String aimPath, String filename) throws IOException {
        ObsClient obsClient = this.getObsClient();
        //    hehehe/aaa
        String oldObjectKey="";
        if(sourcePath.length()==1){
            oldObjectKey = username + sourcePath+filename;
        }else{
            oldObjectKey = username + sourcePath+"/"+filename;
        }

        //列举属于这个文件夹下的对象
        ListObjectsRequest request = new ListObjectsRequest(bucketName);
        request.setPrefix(oldObjectKey);

        ObjectListing result = obsClient.listObjects(request);
        // hehehe/aaa/bbb/   hehehe/aaa/c.txt  hehehe/aaa/bbb/t.png

        for(ObsObject obsObject:result.getObjects()){
            String key = obsObject.getObjectKey();

            if(key.endsWith("/")){      //文件夹   hehehe  /aaa/bbb
                String temp = key.substring(username.length()+sourcePath.length());
                if(temp.equals("")) temp="/";
                String dir_key = username + aimPath + temp;
                System.out.println("dir_key="+dir_key);
                CopyObjectResult  copyObjectResult  = obsClient.copyObject(bucketName,key,bucketName,dir_key);
                obsClient.deleteObject(bucketName,key);

            }else{  //文件
                String temp = key.substring(username.length()+sourcePath.length());
                if(temp.equals("")) temp="/";
                else temp="/"+temp;
                String dir_key = username + aimPath + temp;
                System.out.println("file_key="+dir_key);
                CopyObjectResult  copyObjectResult  = obsClient.copyObject(bucketName,key,bucketName,dir_key);
                obsClient.deleteObject(bucketName,key);
            }

        }
        return true;

    }


    /*
     * @description: 删除文件
     * @param: username
     * @param: path
     * @param: filename
     * @return: boolean
     * @author: Xiong Mian
     * @date: 2020/7/18 20:05
     */
    @Override
    public boolean deleteFile(String username, String path, String filename) {
        ObsClient obsClient = getObsClient();
        String objectKey="";
        if(path.length()==1){
            objectKey = username + path+filename;
        }else{
            objectKey = username + path+"/"+filename;
        }
        DeleteObjectResult deleteObject = obsClient.deleteObject(bucketName, objectKey);
        if (deleteObject == null) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * @description: 重命名文件
     * @param: username
     * @param: path 不包含文件名的路径
     * @param: oldFileName
     * @param: newFileName
     * @return: boolean
     * @author: Xiong Mian
     * @date: 2020/7/18
     */
    @Override
    public boolean renameFile(String username, String path, String oldFileName, String newFileName) throws IOException {
        //获取原文件
        File file = getFile(username, path, oldFileName);
        if (storeFile(username, path, newFileName, new FileInputStream(file)) == true) {
            if (deleteFile(username, path, oldFileName) == true) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /*
     * @description: 预览文件
     * @param: username
     * @param: path
     * @param: filename
     * @return: java.lang.String
     * @author: Xiong Mian
     * @date: 2020/7/18
     */
    @Override
    public String getUrl(String username, String path, String filename) throws IOException {
        ObsClient obsClient = this.getObsClient();
        // 设置预览时长300s
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, 600);
        request.setBucketName(bucketName);
        //主目录下特别处理
        String objectKey="";
        if(path.length()==1){
            objectKey = username + path+filename;
        }else{
            objectKey = username + path+"/"+filename;
        }
        request.setObjectKey(objectKey);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        obsClient.close();
        return response.getSignedUrl();
    }

    @Override
    public InputStream downloadFile(String username, String path, String filename) {
        ObsClient obsClient = this.getObsClient();
        String objectKey="";
        if(path.length()==1){
            objectKey = username + path+filename;
        }else{
            objectKey = username + path+"/"+filename;
        }
        ObsObject obsObject = obsClient.getObject(bucketName, objectKey);
        InputStream content = obsObject.getObjectContent();
        return content;
    }

}

